<template>
  <div ref="chartDom" class="content"></div>
</template>

<script setup lang="ts">
import {debounce} from 'lodash-es'
import echarts from './echarts'

import {onBeforeUnmount, onMounted, ref, watch} from 'vue'

const chartDom = ref()
let myChart: any = null

const props = defineProps({
  chartOptions: Object,
})
//重绘图表函数
const resizeHandler = (): void => {
  myChart.resize()
}

const cancelDebounce = debounce(resizeHandler, 500)

// 设置监听事件
onMounted(() => {
  myChart = echarts.init(chartDom.value)
  window.addEventListener('resize', cancelDebounce)
})

//页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', cancelDebounce)
  myChart.dispose()
})

//监听图表数据时候变化，重新渲染图表
watch(
    () => props.chartOptions,
    () => {
      myChart.setOption(props.chartOptions, true)
    },
    {deep: true}
)
</script>

<style lang="less" scoped>
.content {
  height: 100%;
}
</style>
